package top.api.filter;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import top.api.Constants.SystemConstants;
import top.api.common.ResponseResult;
import top.api.domain.entity.LoginUserDetails;
import top.api.enums.AppHttpCodeEnum;
import top.api.utils.JwtUtil;
import top.api.utils.RedisCache;
import top.api.utils.WebUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 认证过滤器
 */
@Component
@Slf4j
// OncePerRequestFilter 这个过滤器抽象类通常被用于继承实现并在每次请求时只执行一次过滤
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 或header中获取token
        String token = request.getHeader("token");

        // 如果token为空说明该接口不需要登录则直接放行
        if (! StringUtils.hasText(token)){
            chain.doFilter(request,response);
            return;
        }

        // token jwt解析userId
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            //token超时  token非法
            //响应告诉前端需要重新登录
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, JSON.toJSONString(result));
            log.error("jwt解析失败: {}",e.getMessage());
            return;
        }

        String userId = claims.getSubject();

        // 从redis获取LoginUserDetails
        LoginUserDetails loginUser = redisCache.getCacheObject(SystemConstants.REDIS_LOGIN_BLOG_KEY + userId);

        if (Objects.isNull(loginUser)){
            //token超时  token非法
            //响应告诉前端需要重新登录
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, JSON.toJSONString(result));
            return;
        }

        //存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        chain.doFilter(request, response);
    }
}
